from django.db.models import F
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from apps.Base_app.Pagination import BasePagination
from .Serializers import *
from .permissions import CategoryPermission, TagPermission, ArticlePermission


class CategoryViewSet(ModelViewSet, CacheResponseMixin):
    queryset = Category.objects.all()
    serializer_class = CategorySerializers.CreateSerializers
    pagination_class = BasePagination
    filter_backends = [DjangoFilterBackend]
    permission_classes = [CategoryPermission]
    filter_fields = {
        "author": ["exact"],
        "name": ["icontains", "iexact"],
        "language": ["iexact"]
    }

    def get_serializer_class(self):
        if self.action in ["create"]:
            return CategorySerializers.CreateSerializers
        else:
            return CategorySerializers.CategorySerList


class TagViewSet(ModelViewSet, CacheResponseMixin):
    queryset = Tag.objects.all()
    serializer_class = TagSerializers.TagListSerializers
    pagination_class = BasePagination
    permission_classes = [TagPermission]
    filter_backends = [DjangoFilterBackend]
    filter_fields = {
        "name": ["icontains", "iexact"],
        "author": ["exact"],
    }

    def get_serializer_class(self):
        if self.action in ["create"]:
            return TagSerializers.TagCreateSerializers
        return TagSerializers.TagListSerializers


class ArticleViewSet(ModelViewSet, CacheResponseMixin):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializers.ArticleListSerializers
    pagination_class = BasePagination
    permission_classes = [ArticlePermission]
    filter_backends = [DjangoFilterBackend]
    filter_fields = {
        "title": ["icontains", "iexact"],
        "body": ["icontains", "iexact"],
        "author": ["exact"],
        "category": ["exact"],
        "tags": ['exact'],
        "status": ["exact"]
    }

    def get_serializer_class(self):
        if self.action in ['create']:
            return ArticleSerializers.ArticleCreateSerializers
        else:
            return ArticleSerializers.ArticleListSerializers

    def retrieve(self, request, *args, **kwargs):
        _object = self.get_object()
        _object.views = F("views") + 1
        _object.save()
        _serializer = ArticleSerializers.ArticleListSerializers(self.queryset.get(id=_object.id), many=False)
        return Response(_serializer.data, status=status.HTTP_200_OK)
